package com.x.ant.util;

import com.itextpdf.text.*;
import com.itextpdf.text.pdf.*;
import com.x.ant.model.BillTruck;
import com.x.ant.model.Task;
import com.x.ant.model.Truck;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;


public class BillPdfUtil {

    public static void main(String[] args) throws Exception {
        BillPdfUtil pdfUtil = new BillPdfUtil();
//        String pdf = pdfUtil.createPDF();
//        pdfUtil.imageWaterMark(pdf, "E://xspace//ant//bg.png");
//        pdfUtil.stringWaterMark(pdf, "黑蚁优服");
    }


    /**
     * 创建PDF文档
     *
     * @return
     * @throws Exception
     */
    public File createPDF(String deptName, String billCode, Task task, List<BillTruck> billTruckList, File pdf) throws Exception {

        //设置纸张
        Rectangle rect = new Rectangle(PageSize.A4);

        //创建文档实例
        Document doc = new Document(rect);

        //添加中文字体
        BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
        BaseColor colorRed = new BaseColor(255, 0, 0);

        //设置字体样式
        Font noramlFont = new Font(bfChinese, 12, Font.NORMAL); //正常
        Font redFont = new Font(bfChinese, 12, Font.NORMAL, colorRed); //正常,红色
        Font boldFont = new Font(bfChinese, 12, Font.BOLD); //加粗
        Font redBoldFont = new Font(bfChinese, 12, Font.BOLD, colorRed); //加粗,红色
        Font firsetTitleFont = new Font(bfChinese, 22, Font.BOLD); //一级标题
        Font secondTitleFont = new Font(bfChinese, 15, Font.BOLD); //二级标题
        Font underlineFont = new Font(bfChinese, 12, Font.UNDERLINE); //下划线斜体

        //创建输出流
        PdfWriter.getInstance(doc, new FileOutputStream(pdf));

        doc.open();
        doc.newPage();

        //段落
        Paragraph p1 = new Paragraph();
        //短语
        Phrase ph1 = new Phrase();

        ph1.add(new Chunk(leftPad(billCode, 7), noramlFont));
        p1.add(ph1);
        doc.add(p1);

        p1 = new Paragraph(deptName + "货运协议", firsetTitleFont);
        p1.setLeading(50);
        p1.setAlignment(Element.ALIGN_CENTER);
        doc.add(p1);

        p1 = new Paragraph();
        ph1 = new Phrase();
        ph1.add(new Chunk(task.getTaskSenderUserName() + " " + task.getTaskSenderUserMobile(), noramlFont).setSkew(0, 30));
        ph1.add(new Chunk(task.getTaskLoadingArea() + task.getTaskLoadingAddress(), noramlFont).setSkew(0, 30));
        ph1.add(new Chunk(task.getTaskUnloadingArea() + task.getTaskUnloadingAddress(), noramlFont).setSkew(0, 30));
        p1.add(ph1);
        doc.add(p1);

        p1 = new Paragraph();
        ph1 = new Phrase();
        ph1.add(new Chunk(task.getTaskGoodsStandard(), noramlFont));
        p1.add(ph1);
        doc.add(p1);

        ph1.add(new Chunk(task.getTaskCostPrice().toString(), noramlFont));
        ph1.add(new Chunk(task.getTaskPayWay(), noramlFont));
        String truckPlate = "";
        String truckUserName = null;
        String truckMobile = null;
        String truckNative = null;
        for (BillTruck billTruck : billTruckList) {
            if(truckUserName == null) {
                truckUserName = billTruck.getUserName();
            }
            if(truckMobile == null) {
                truckMobile = billTruck.getTruck().getTruckMobile();
            }
            if(truckNative == null) {
                truckNative = billTruck.getTruck().getTruckNative();
            }
            truckPlate += billTruck.getTruck().getTruckPlateHeader() + billTruck.getTruck().getTruckPlateMiddle() + " " + billTruck.getTruck().getTruckPlateCode() + " ";
        }
        ph1.add(new Chunk(truckPlate, noramlFont));
        ph1.add(new Chunk(truckUserName, noramlFont));
        ph1.add(new Chunk(truckMobile, noramlFont));
        ph1.add(new Chunk(truckNative, noramlFont));
               p1.add(ph1);
        doc.add(p1);

        p1 = new Paragraph("信息主体实缴资本**万元，****年**月**日股东****公司向***公司转让**万元股权。", noramlFont);
        p1.setFirstLineIndent(23);
        p1.setSpacingBefore(20);
        p1.setSpacingAfter(15);
        doc.add(p1);


        doc.close();
        return pdf;
    }


    /**
     * 加水印（字符串）
     *
     * @param inputFile     需要加水印的PDF路径
     * @param waterMarkName 水印字符
     */
    private void stringWaterMark(String inputFile, String waterMarkName) {
        try {
            String[] spe = this.separatePath(inputFile);
            String outputFile = spe[0] + "_WM." + spe[1];

            PdfReader reader = new PdfReader(inputFile);
            PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(outputFile));
            //添加中文字体
            BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
            int total = reader.getNumberOfPages() + 1;
            PdfContentByte under;
            int j = waterMarkName.length();
            char c = 0;
            int rise = 0;
            //给每一页加水印
            PdfGState gs = new PdfGState();
            gs.setFillOpacity(0.1f);// 设置透明度为0.2
            for (int i = 1; i < total; i++) {
//                rise = 780;
                under = stamper.getUnderContent(i);
                under.beginText();
                under.setFontAndSize(bfChinese, 30);
                under.setTextMatrix(450, 800);
                for (int k = 0; k < j; k++) {
//                    under.setTextRise(rise);
                    c = waterMarkName.charAt(k);
                    under.showText(c + "");
                }
                under.setGState(gs);
                // 添加水印文字
                under.endText();
            }
            stamper.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 加水印（图片）
     *
     * @param inputFile 需要加水印的PDF路径
     * @param imageFile 水印图片路径
     */
    public void imageWaterMark(String inputFile, String imageFile) {
        try {
            String[] spe = this.separatePath(inputFile);
            String outputFile = spe[0] + "_IWM." + spe[1];

            PdfReader reader = new PdfReader(inputFile);
            PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(outputFile));

            int total = reader.getNumberOfPages() + 1;

            Image image = Image.getInstance(imageFile);
            image.setAbsolutePosition(-100, 0);//坐标
            image.scaleAbsolute(800, 1000);//自定义大小
            image.setAlignment(Image.ALIGN_CENTER);
            //image.setRotation(-20);//旋转 弧度
            //image.setRotationDegrees(-45);//旋转 角度
            //image.scalePercent(50);//依照比例缩放

            PdfGState gs = new PdfGState();
            gs.setFillOpacity(0.9f);// 设置透明度为0.2


            PdfContentByte under;
            //给每一页加水印
            for (int i = 1; i < total; i++) {
                under = stamper.getUnderContent(i);
                under.beginText();
                // 添加水印图片
                under.addImage(image);
                under.setGState(gs);
            }
            stamper.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 设置左边距
     *
     * @param str
     * @param i
     * @return
     */
    private String leftPad(String str, int i) {
        int addSpaceNo = i - str.length();
        String space = "";
        for (int k = 0; k < addSpaceNo; k++) {
            space = " " + space;
        }
        ;
        String result = space + str;
        return result;
    }

    /**
     * 分割路径
     *
     * @param path
     * @return 返回分割后的路径
     */
    private String[] separatePath(String path) {
        if (org.apache.commons.lang3.StringUtils.isBlank(path)) {
            return null;
        }
        String[] sep = path.split("\\.");
        return new String[]{sep[0], sep[1]};
    }

}
